package com.sharelords.icp.web.service.impl;

import com.sharelords.dynamic.loader.entrance.ClassSrcOpera;
import com.sharelords.icp.web.aop.LogExportProxy;
import com.sharelords.icp.web.constant.ReturnCodeEnum;
import com.sharelords.icp.web.result.ViewResult;
import com.sharelords.icp.web.result.helper.ViewResultHelper;
import com.sharelords.icp.web.service.IcpService;
import com.sharelords.icp.web.util.JavaFileSrcUtil;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.MessageFormat;

/**
 * @author 夜舞旋
 */
@Service
public class IcpServiceImpl implements IcpService {

    private static final String EXCEPTION_CLAIM = "程序有错，或者使用了System.in输入，请仔细检查源代码，错误信息如下：\n{0}";
    private static final String ILLEGAL_OPERA = "非法操作，不支持System.in流形式输入，错误信息如下：\n{0}";

    static {
        try {
            // 禁用流输入
            System.in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ViewResult<String> mainExecute(String fileSrc) {
        try {
            // 获取代理对象
            LogExportProxy<ClassSrcOpera> proxy = new LogExportProxy<>();
            ClassSrcOpera classSrcOpera = proxy.getInstance(ClassSrcOpera.getInstance());
            // 执行方法
            classSrcOpera.mainMethodInvoke(fileSrc, JavaFileSrcUtil.getFileName(fileSrc));

            return ViewResultHelper.success(proxy.getSystemOutPrintStr());
        } catch (Exception e) {
            Thread.interrupted();
            return ViewResultHelper.failed(ReturnCodeEnum.ERROR, MessageFormat.format(EXCEPTION_CLAIM, e.toString()));
        }
    }

}
